<template>
  <el-card header="聊天历史管理 (Chat History API)" class="mb-4">
    <p class="text-sm text-gray-500 mb-4">
      这些 API 通常用于后端服务间的聊天记录同步。
      <el-tag size="small">当前测试会话ID: {{ sessionId }}</el-tag>
      <el-tag size="small" type="info">用户ID: {{ accountId }}</el-tag>
    </p>

    <div class="flex space-x-4">
      <el-button type="success" @click="handleAddMessage" :loading="addLoading">
        {{ addLoading ? '添加中...' : '模拟添加一条消息' }}
      </el-button>

      <el-button type="danger" plain @click="handleDeleteSession" :loading="deleteLoading">
        {{ deleteLoading ? '删除中...' : '删除整个会话历史' }}
      </el-button>
    </div>

    <el-alert
      v-if="statusMessage"
      :title="statusMessage.title"
      :type="statusMessage.type"
      show-icon
      closable
      class="mt-4"
      @close="statusMessage = null"
    />
  </el-card>
</template>

<script setup lang="ts">
import { ref } from 'vue';
// 确保路径正确，Nuxt 通常会自动处理别名
import { addChatMessage, deleteChatMessages, type AddChatMessagePayload } from '~/api/chatHistoryApi'; 
import { ElMessage } from 'element-plus';

interface AlertMessage {
  title: string;
  type: 'success' | 'error' | 'warning' | 'info';
}

const sessionId = ref('user_session_123');
const accountId = ref('user_456');

const addLoading = ref(false);
const deleteLoading = ref(false);
const statusMessage = ref<AlertMessage | null>(null); 

const setStatusMessage = (title:any, type: AlertMessage['type'] = 'success') => {
  statusMessage.value = { title, type };
  setTimeout(() => { statusMessage.value = null; }, 5000);
};

// 添加一条消息
const handleAddMessage = async () => {
  addLoading.value = true;
  try {
    const payload: AddChatMessagePayload = {
      session_id: sessionId.value,
      account_id: accountId.value,
      role: 'user',
      content: '模拟用户提问：请帮我查询一份检察院相关文件。',
      timestamp: new Date().toISOString()
    };
    const result = await addChatMessage(payload);
    
    setStatusMessage(`成功: ${result.message}`, 'success');
  } catch (error) {
    let errorMessage = '未知错误';
    if (error instanceof Error) {
      errorMessage = error.message;
    }
    setStatusMessage(`添加消息失败: ${errorMessage}`, 'error');
  } finally {
    addLoading.value = false;
  }
};

// 示例：删除整个会话
const handleDeleteSession = async () => {
  deleteLoading.value = true;
  try {
    const payload = {
      session_id: sessionId.value,
      account_id: accountId.value
    };
    const result = await deleteChatMessages(payload);
    
    setStatusMessage(`成功: ${result.message}`, 'warning');
  } catch (error) {
    let errorMessage = '未知错误';
    if (error instanceof Error) {
      errorMessage = error.message;
    }
    setStatusMessage(`删除会话失败: ${errorMessage}`, 'error');
  } finally {
    deleteLoading.value = false;
  }
};
</script>